<template>
  <el-dialog style="height:100vh" width="72%" top="0" :title="title" :close-on-click-modal="false" :visible.sync="visible" @close="clearImg">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="商品名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="dataForm.status" placeholder="状态" clearable style="width: 100%">
              <el-option v-for="(i,index) in ['已下架','已上架']" :key="index" :label="i" :value="index" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品类型" prop="goodsType">
            <el-cascader v-model="goodsType" :options="typeList" :props="{
                  value:'id',
                  label:'name',
                  multiple:true
                }" @change="selectGoodsType" style="width:100%"></el-cascader>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商品单位" prop="unit">
            <el-input v-model="dataForm.unit" placeholder="商品单位"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商品销量" prop="sale">
            <el-input v-model="dataForm.remark" placeholder="商品销量"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品缩略图" prop="picturePath">
            <image-upload ref="picturePath" :type="'image'" :imageLimitSize="4" :imageSize="1" :imgageList="picturePath"
              @updateImg="changeImg('2',$event)" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="商品图片" prop="imgList">
            <image-upload ref="imgList" :type="'image'" :imageLimitSize="4" :imageSize="5" :imgageList="imgList" multiple
              @updateImg="changeImg('1',$event)" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品详情" prop="goodsIntroduce">
            <RichTextBox :content="dataForm.goodsIntroduce" @update="changeContent" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="商品规格">
          <el-table border height="280" :data="dataForm.skuList" style="width:100%">
            <el-table-column prop="name" label="规格名称" width="260" align="center">
              <template slot-scope="scope">
                <el-input placeholder="请输入规格名称" type="text" v-model="scope.row.name" size="mini" />
              </template>
            </el-table-column>
            <el-table-column prop="picturePath" label="规格图片" width="100" align="center">
              <template slot-scope="scope">
                <img src="@/assets/images/image.png" class="sku_img" @click="clickBtn(scope.$index)"
                  v-if="!scope.row.picturePath" />
                <img @click="clickBtn(scope.$index)" class="sku_img" v-lazy="imageApi + scope.row.picturePath"
                  style="height:40px" v-else />
                <input type="file" :ref="'skuImg'+scope.$index" class="sku_img_upload"
                  @change="uploadImg(scope.$index)" />
              </template>
            </el-table-column>
            <el-table-column prop="goodsPriceCurrent" label="销售价" width="166" align="center">
              <template slot-scope="scope">
                <el-input-number :precision="2" :step="0.01" :min="0" :max="999999"
                  v-model="scope.row.goodsPriceCurrent" size="mini" />
              </template>
            </el-table-column>
            <el-table-column prop="goodsPriceOriginal" label="划线价" width="166" align="center">
              <template slot-scope="scope">
                <el-input-number :precision="2" :step="0.01" :min="0" :max="999999"
                  v-model="scope.row.goodsPriceOriginal" size="mini" />
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="库存数量" width="166" align="center">
              <template slot-scope="scope">
                <el-input-number :precision="0" :step="1" :min="1" :max="999999" v-model="scope.row.quantity"
                  size="mini" />
              </template>
            </el-table-column>
            <el-table-column prop="sale" label="已售数量" width="166" align="center">
              <template slot-scope="scope">
                <el-input-number :precision="0" :step="1" :min="0" :max="999999" v-model="scope.row.sale" size="mini" />
              </template>
            </el-table-column>
            <el-table-column prop="defaultPrice" label="默认选中" align="center">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.defaultPrice" active-text="是" inactive-text="否"
                  @change="changeSwitch(scope.row)" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
                  :inactive-value="0">
                </el-switch>
                <!-- <div class="check_box" @click="selectDefaultGoods(scope.row.defaultPrice,scope.$index)">
                  <el-icon class="el-icon-check" style="color:red" v-if="scope.row.defaultPrice == 1"></el-icon>
                </div> -->
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作" align="right">
              <template slot-scope="scope">
                <el-link type="primary" @click="addSku" v-if="scope.$index == dataForm.skuList.length-1">添加 </el-link>
                <span style="margin-right:5px;"></span>
                <el-link type="danger" @click="delSku(scope.$index)"> 删除</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button :loading="loading" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    upload
  } from '@/api/file'
  import {
    addOrUpdate
  } from "@/api/business/goods/goods";
  import {
    getType
  } from "@/api/business/goods/type";
  import RichTextBox from '@/components/RichTextBox/index.vue'
  export default {
    components: {
      RichTextBox
    },
    dicts: ['order_status'],
    data() {
      return {
        title: '',
        loading: false,
        visible: false,
        hasDefault: false,
        couponArr: [{
          code: 0,
          name: '否'
        }, {
          code: 1,
          name: '是'
        }],
        dataForm: {
          goodsIntroduce: '',
          goodsType: []
        },
        goodsType: [],
        imageApi: process.env.VUE_APP_IMAGE_BASE_URL,
        imgList: [],
        picturePath: [],
        typeList: [],
        dataRule: {
          name: [{
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }],
          goodsType: [{
            required: true,
            message: '请输入商品类型',
            trigger: 'blur'
          }],
          unit: [{
            required: true,
            message: '请输入商品单位',
            trigger: 'blur'
          }],

          goodsIntroduce: [{
            required: true,
            message: '请输入商品介绍',
            trigger: 'blur'
          }],
          quantity: [{
            required: true,
            message: '请输入库存数量',
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      changeSwitch(item) {
        if (item.defaultPrice == 1) {
          this.hasDefault = true
          this.dataForm.skuList.forEach(res => {
            if (res.id !== item.id) res.defaultPrice = 0
          })
        } else {
          this.hasDefault = false
        }
      },
      clickBtn(e) {
        this.$refs['skuImg' + e].click();
      },
      uploadImg(e) {
        let files = window.event.target.files[0];
        let formData = new FormData();
        formData.append('file', files)
        upload(formData).then(res => {
          this.dataForm.skuList[e].picturePath = res.data.path
        })
      },
      selectGoodsType(e) {
        console.log('goodsType', e)
        // const list = this.dataForm.goodsType;
        // console.log('list',list)
        // list.push(e[e.length-1])
        // this.dataForm.goodsType = list;
      },
      selectDefaultGoods(e, index) {
        if (e == 1) {
          console.log('e', e)
          return
        }
        for (var i = 0; i < this.dataForm.skuList.length; i++) {
          this.dataForm.skuList[i].defaultPrice = 0;
        }
        this.dataForm.skuList[index].defaultPrice = 1;
      },
      addSku(e) {
        const list = this.dataForm.skuList
        list.push({
          name: '',
          goodsPriceOriginal: 0,
          goodsPriceCurrent: 0,
          defaultPrice: 0,
          picturePath: '',
          quantity: 1,
          sale: 1
        });
        //   console.log(this.dataForm.skuList.length)
        // this.$forceUpdate();
        this.$set(this.dataForm, 'skuList', list)
      },
      delSku(e) {
        if (this.dataForm.skuList.length <= 1) {
          return
        }
        this.$confirm('确定要删除这项规格吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => {
          if (this.dataForm.skuList[e].defaultPrice === 1) {
            this.hasDefault = false
          }
          this.dataForm.skuList.splice(e, 1)
        })
      },
      changeContent(val) {
        this.dataForm.goodsIntroduce = val.value
      },
      clearImg(e) {
        this.imgList = [];
        this.picturePath = []
        this.$refs.imgList.init([])
        this.$refs.picturePath.init([])
      },
      setGoodsType(id, list, itemList) {
        const item = itemList;
        for (var i = 0; i < list.length; i++) {
          // console.log(id,list[i].id)
          item.push(list[i].id)
          if (id == list[i].id) {
            return item;
          } else {
            if (list[i].children) {
              this.setGoodsType(id, list[i].children, item);
            }
          }
        }
      },
      init(record) {
        this.visible = true
        this.dataForm = record
        if (this.dataForm && this.dataForm.id) {
          this.title = '商品信息表' + '修改'
          if (this.dataForm.goodsRotator) {
            this.$nextTick(() => {
              for (var i = 0; i < this.dataForm.goodsRotator.length; i++) {
                this.imgList.push({
                  url: this.imageApi + this.dataForm.goodsRotator[i],
                  filePath: this.dataForm.goodsRotator[i],
                })
              }
              // this.$refs.imgList.init(this.imgList)
            })
          }
          if (this.dataForm.picturePath) {
            this.$nextTick(() => {
              this.picturePath.push({
                url: this.imageApi + this.dataForm.picturePath,
                filePath: this.dataForm.picturePath
              })
            })
          }
        } else {
          this.title = '商品信息表' + "新增"
          this.dataForm.goodsType = []
          this.dataForm.status = 1
          const list = [{
            name: '',
            goodsPriceOriginal: 0,
            goodsPriceCurrent: 0,
            defaultPrice: 1,
            picturePath: ''
          }];
          this.$set(this.dataForm, 'skuList', list)
        }
        getType({
          status: 1
        }).then(res => {
          this.typeList = res.data;
          // this.typeList = this.setTypeList(this.typeList)

          const goodsType = [];
          for (var i = 0; i < this.dataForm.goodsType.length; i++) {
            const item = new Array()
            for (var j1 = 0; j1 < this.typeList.length; j1++) {

              if (this.typeList[j1].id == this.dataForm.goodsType[i]) {
                item.push(this.dataForm.goodsType[i])
                break;
              } else {
                if (this.typeList[j1].children) {
                  const typeList2 = this.typeList[j1].children;
                  for (var j2 = 0; j2 < typeList2.length; j2++) {
                    if (typeList2[j2].id == this.dataForm.goodsType[i]) {
                      item.push(this.typeList[j1].id)
                      item.push(this.dataForm.goodsType[i])
                      break;
                    } else {
                      if (typeList2[j2].children) {
                        const typeList3 = typeList2[j2].children;
                        for (var j3 = 0; j3 < typeList3.length; j3++) {
                          if (typeList3[j3].id == this.dataForm.goodsType[i]) {
                            item.push(this.typeList[j1].id)
                            item.push(typeList2[j2].id)
                            item.push(this.dataForm.goodsType[i])
                            break;
                          }
                        }
                      }
                    }
                  }
                }
              }
            }

            if (item.length > 0) {
              goodsType.push(item)
            }
          }

          this.goodsType = goodsType
        })
      },
      setTypeList(e) {
        const list = e;
        for (var i = 0; i < list.length; i++) {
          if (list[i].children.length == 0) {
            delete list[i].children
          } else {
            list[i].children = this.setTypeList(list[i].children)
          }
        }

        return list;
      },
      changeImg(val, e) {
        if (val == '1') {
          this.imgList = e
        } else if (val == '2') {
          this.picturePath = e
        }
      },
      // 表单提交
      dataFormSubmit() {
        this.loading = true
        if (this.goodsType.length == 0) {
          this.$message.error('请至少选择一种商品类型')
          this.loading = false
          return false;
        }
        const goodsType = new Array();
        for (var i = 0; i < this.goodsType.length; i++) {
          goodsType.push(this.goodsType[i][this.goodsType[i].length - 1])
        }
        this.dataForm.goodsType = goodsType;
        const list = new Array()
        if (this.picturePath.length == 0) {
          this.$message.error('请添加商品缩略图');
          this.loading = false
          return
        }
        if (this.imgList.length == 0) {
          this.$message.error('请至少添加一张商品图片');
          this.loading = false
          return
        }
        for (var i = 0; i < this.imgList.length; i++) {
          list.push(this.imgList[i].filePath);
        }
        this.dataForm.goodsRotator = list;
        this.dataForm.picturePath = this.picturePath[0].filePath;
        let skuList = this.dataForm.skuList
        let hasDefault = false
        skuList.forEach(item => {
          hasDefault = (item.defaultPrice === 1)
          if (hasDefault) {
            return true;
          }
        })
        if (!hasDefault) {
          this.$message({
            message: '商品规格必须有一个条为默认选中！',
            type: 'warning'
          });
          this.loading = false
          return
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addOrUpdate(this.dataForm).then(res => {
              this.visible = false
              this.loading = false
              this.$modal.msgSuccess(this.title + "成功");
              this.$emit('refreshDataList')
            }).catch(err => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        })
      }
    }
  }
</script>
<style scoped>
  .check_box {
    width: 16px;
    height: 16px;
    border: 1px solid #aaa;
    margin: 0 auto;
    line-height: 16px;
  }

  .sku_img {
    width: 50px;
  }

  .sku_img_upload {
    display: none;
  }
</style>